//
//  WithdrawController.m
//  EasyCar
//
//  Created by nsm on 2018/1/9.
//  Copyright © 2018年 beisheng. All rights reserved.
//

#import "WithdrawController.h"
#import "BindCardListController.h"
#import "WithDrawListController.h"

@interface WithdrawController () <UITextFieldDelegate> {
    NSDictionary    *_carInfo;
    UIImageView     *_iconImageView;
    UILabel         *_titleLabel;
    UIButton        *_chooseBtn;
    MyLinearLayout  *_cardLayout;
    
    NSString        *_maxValue;
    UILabel         *_validLabel;
    UITextField     *_moneyField;
    NSMButton       *_submitBtn;
    MyBaseLayout    *_rootLayout;
}
@end

@implementation WithdrawController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initNavigationItems];
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.myHorzMargin = 0;
    layout.padding = UIEdgeInsetsMake(15, 0, 15, 0);
    [self.view addSubview:layout];
    _rootLayout = layout;
    
    [self requestData];
}

- (void)initNavigationItems {
    UIBarButtonItem *rechargeItem = [[UIBarButtonItem alloc] initWithTitle:@"记录"
                                                                     style:UIBarButtonItemStylePlain
                                                                    target:self
                                                                    action:@selector(showList)];
    self.navigationItem.rightBarButtonItem = rechargeItem;
}

- (void)createUI:(NSDictionary *)obj {
    [_rootLayout removeAllSubviews];
    
    _maxValue = ReplaceString(obj[@"balance"], @"0.00");
    
    UIView *cardView = [self cardView:obj[@"bank"]];
    [_rootLayout addSubview:cardView];
    
    MyLinearLayout *moneyLayout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    moneyLayout.backgroundColor = [UIColor whiteColor];
    moneyLayout.myHorzMargin = 0;
    moneyLayout.myTop = 20;
    moneyLayout.padding = UIEdgeInsetsMake(10, 15, 0, 15);
    [_rootLayout addSubview:moneyLayout];
    
    UILabel *label = [UILabel new];
    label.myHorzMargin = 0;
    label.wrapContentHeight = YES;
    label.textColor = [UIColor darkGrayColor];
    label.font = CustomFont(14);
    label.text = @"提现金额";
    [moneyLayout addSubview:label];
    
    _moneyField = [UITextField new];
    _moneyField.myTop = 4;
    _moneyField.myHeight = 44;
    _moneyField.myHorzMargin = 0;
    _moneyField.delegate = self;
    _moneyField.textColor = THEME_COLOR;
    _moneyField.font = BoldSystemFont(36);
    _moneyField.keyboardType = UIKeyboardTypeDecimalPad;
    _moneyField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [moneyLayout addSubview:_moneyField];
    
    @nsm_weak(self)
    [_moneyField addBlockForControlEvents:UIControlEventEditingChanged block:^(id  _Nonnull sender) {
        @nsm_strong(self)
        [self checkEnable];
    }];
    
    UILabel *left = [UILabel new];
    left.myHeight = 44;
    left.myHorzMargin = 0;
    left.textColor = THEME_COLOR;
    left.font = BoldSystemFont(30);
    left.text = @"¥";
    [left sizeToFit];
    left.width += 4;
    
    _moneyField.leftView = left;
    _moneyField.leftViewMode = UITextFieldViewModeAlways;
    
    UIView *line = [UIView new];
    line.myHorzMargin = 0;
    line.myHeight = [MyDimeScale roundNumber:0.6];
    line.backgroundColor = SEPARATOR_COLOR;
    [moneyLayout addSubview:line];
    
    MyLinearLayout *bottomLayout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
    bottomLayout.myHorzMargin = 0;
    bottomLayout.myHeight = 32;
    bottomLayout.gravity = MyGravity_Vert_Center;
    [moneyLayout addSubview:bottomLayout];
    
    UILabel *validLabel = [UILabel new];
    validLabel.weight = 1;
    validLabel.font = CustomFont(13);
    validLabel.text = FormatString(@"可用余额 %@元", _maxValue);
    validLabel.textColor = [UIColor lightGrayColor];
    validLabel.wrapContentHeight = YES;
    [bottomLayout addSubview:validLabel];
    _validLabel = validLabel;
    
    UIButton *totalBtn = [UIButton new];
    totalBtn.wrapContentSize = YES;
    totalBtn.titleLabel.font = CustomFont(14);
    [totalBtn setTitleColor:THEME_COLOR forState:UIControlStateNormal];
    [totalBtn setTitle:@"全部提现" forState:UIControlStateNormal];
    [totalBtn addTarget:self action:@selector(takeOffAll) forControlEvents:UIControlEventTouchUpInside];
    [bottomLayout addSubview:totalBtn];
    
    _submitBtn = [NSMButton buttonWithTitle:@"确 定" target:self action:@selector(submit)];
    _submitBtn.myHorzMargin = 40;
    _submitBtn.myTop = 40;
    [_rootLayout addSubview:_submitBtn];
}

- (UIView *)cardView:(id)info {
    UIView *bgView = [UIView new];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.size = CGSizeMake(kScreenWidth, 64);
    bgView.mySize = CGSizeMake(kScreenWidth, 64);
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
    layout.mySize = CGSizeMake(bgView.width, 64);
    layout.padding = UIEdgeInsetsMake(0, 15, 0, 15);
    layout.subviewHSpace = 12;
    layout.gravity = MyGravity_Vert_Center;
    [bgView addSubview:layout];
    _cardLayout = layout;
    
    UIImageView *iconImageView = [UIImageView new];
    iconImageView.mySize = CGSizeMake(40, 40);
    [layout addSubview:iconImageView];
    _iconImageView = iconImageView;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.weight = 1;
    titleLabel.wrapContentHeight = YES;
    [layout addSubview:titleLabel];
    _titleLabel = titleLabel;
    
    [layout addSubview:ArrowImageView(SUB_TEXT_COLOR, 1)];
    
    _chooseBtn = [UIButton new];
    _chooseBtn.size = bgView.size;
    _chooseBtn.titleLabel.font = BoldSystemFont(18);
    [_chooseBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [_chooseBtn addTarget:self action:@selector(choose) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:_chooseBtn];
    
    [self refreshUI:info];
    
    return bgView;
}

- (void)refreshUI:(NSDictionary *)info {
    if (info.count) {
        [_iconImageView setImageURL:info[@"logo"]];
        _titleLabel.attributedText = [self titleString:info];
        
        _chooseBtn.backgroundColor = [UIColor clearColor];
        [_chooseBtn setTitle:@"" forState:UIControlStateNormal];
    } else {
        _chooseBtn.backgroundColor = [UIColor clearColor];
        [_chooseBtn setTitle:@"请选择银行卡" forState:UIControlStateNormal];
    }
    
    _carInfo = info;
    [self checkEnable];
}

- (NSAttributedString *)titleString:(NSDictionary *)obj {
    NSUInteger len = [obj[@"card"] length];
    NSRange range;
    if (len <= 4)
        range = NSMakeRange(0, len);
    else
        range = NSMakeRange(len-4, 4);
    NSString *card = [obj[@"card"] substringWithRange:range];
    card = FormatString(@"\n**** %@ (%@)",card, obj[@"name"]);
    return AttributedString(obj[@"bank_name"],
                            BoldSystemFont(16),
                            [UIColor darkGrayColor],
                            card,
                            CustomFont(14),
                            [UIColor darkGrayColor],
                            NSTextAlignmentLeft,
                            2);
}

#pragma mark - Data
- (void)requestData {
    // 获取用户默认银行卡
    [_networker POST:@"mine/defaultCard.html" parameters:nil success:^(NSMResponseObject *responseObject) {
        [self createUI:responseObject.data];
    } empty:nil failure:nil];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = SafeString(textField.text);
    // 不允许.开头
    if (!text.length && [string isEqual:@"."]) return NO;
    // 不允许多个.
    if ([text containsString:@"."] && [string isEqual:@"."])
        return NO;
    // 不允许连续2个0开头
    if (text.length == 1 && [text isEqual:@"0"] && [string isEqual:@"0"]) return NO;
    
    NSArray *array = [text componentsSeparatedByString:@"."];
    if (array.count == 2) {
        NSString *suffix = array[1];
        // 小数点后面只允许输入2位
        if (suffix.length == 2) {
            if (string.length) return NO;
        }
    }
    return YES;
}

- (void)checkEnable {
    NSString *text = _moneyField.text;
    BOOL valide = (text.doubleValue <= _maxValue.doubleValue);
    if (valide) {
        _validLabel.text = FormatString(@"可提现收益 ¥%@", _maxValue);
        _validLabel.textColor = [UIColor lightGrayColor];
    } else {
        _validLabel.text = @"已超过可提现金额";
        _validLabel.textColor = [UIColor redColor];
    }
    BOOL enable =  valide && _carInfo && (text.doubleValue > 0);

    _submitBtn.enabled = enable;
}

- (void)choose {
    BindCardListController *vc = [BindCardListController new];
    vc.title = @"已绑定银行卡";
    vc.didSelectedCard = ^(id obj) {
        [self refreshUI:obj];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)takeOffAll {
    _moneyField.text = _maxValue;
    [self checkEnable];
}

- (void)submit {
    [self.view endEditing:YES];
    
    @nsm_weak(self)
    [self showAlert:@"确定要提现吗?" cancel:nil done:^(UIAlertAction *action) {
        @nsm_strong(self)
        [self submitDone];
    }];
}

- (void)submitDone {
    NSDictionary *param = @{@"bank": SafeString(_carInfo[@"id"]),
                            @"money": FormatString(@"%.2lf",_moneyField.text.floatValue)};
    @nsm_weak(self)
    [_networker POST:@"mine/withdrawals.html" parameters:param success:^(NSMResponseObject *responseObject) {
        @nsm_strong(self)
        [self showAlert:responseObject.desc action:^(UIAlertAction *action) {
            !self.didSubmitSuccess?:self.didSubmitSuccess();
            [self.navigationController popViewControllerAnimated:YES];
        }];
    } empty:nil failure:nil];
}

- (void)showList {
    WithDrawListController *vc = [WithDrawListController new];
    vc.title = @"提现记录";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
